package com.liws.hellojuc.reentrantReadWriteLock;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author ：liweisheng
 * @date ：2022/2/9 21:14
 * @description：
 */
public class ReentrantReadWriteLockTest03 {

    public static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public static ReentrantReadWriteLock.ReadLock readLock = lock.readLock();

    public static ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();

    static class ReadThreadDemo implements Runnable{

        private String name;

        public ReadThreadDemo(String name){
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println(name + "开始" + getDate());
            readLock.lock();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            readLock.unlock();
            System.out.println(name + "结束" + getDate());
        }
    }

    static class WriteThreadDemo implements Runnable{

        private String name;

        public WriteThreadDemo(String name){
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println(name + "开始" + getDate());
            writeLock.lock();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            writeLock.unlock();
            System.out.println(name + "结束" + getDate());
        }
    }
    public static String getDate(){
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        return  dateFormat.format(date);
    }

    public static void main(String []args){
        ThreadPoolExecutor threadPoolExecutor =  new ThreadPoolExecutor(3, 3,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        threadPoolExecutor.execute(new ReadThreadDemo("task-0"));
        threadPoolExecutor.execute(new WriteThreadDemo("task-1"));
        threadPoolExecutor.shutdown();
    }
}
